<!--
 * @Descripttion: 出手鸭小程序
 * @version:1.0.1
 * @Author: HHL
 * @Date: 2023-10-10 10:52:20
 * @LastEditTime: 2025-09-29 10:07:05
 * @LastEditors: sueRimn
-->


<template>
  <page-meta 
    :page-style="'overflow:' + (showRetainDialog ? 'hidden' : 'visible')"
    @resize="onResize"
  />
  <view class="evaluate d-flex flex-column">
    <!-- #ifdef H5 -->
    <custom-navbar title="高价出手" @left-click="handleCustomBack" />
    <!-- #endif -->
    <!-- #ifndef H5 -->
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left" @click="handleCustomBack">
          <uni-icons type="back" size="24" color="#333"></uni-icons>
        </view>
        <view class="navbar-title">高价出手</view>
        <view class="navbar-right"></view>
      </view>
    </view>
    <!-- #endif -->
    
    <!-- 商品信息 -->
    <!-- {{ selectCoupon }} -->
    <product-info :evaluate="evaluate" :basePrice="basePrice" :displayPrice="displayPrice" :selectCoupon="selectCoupon" :couponList="couponList"
      @handleSwitchCoupon="handleLayerShow('couponRef')" :countDown="countDown"/>

    <!--加价券-->
    <coupon-vue :selectCoupon="selectCoupon" :couponList="couponList" @handleGrent="handleCouponGrent" />

    <!--卖点-->
    <!-- <tips-vue /> -->


    <!--芝麻速办-->
    <!-- #ifdef MP-ALIPAY -->
    <!-- <zhima-suban :advanceCharge="zhima_advanceCharge" /> -->
    <!-- #endif -->
    <!-- 回收方式 -->
    <recycle-method :noVisit="noVisit" :wayList="wayList" :wayIndex="wayIndex" :addressInfo="addressInfo"
      :accountInfo="accountInfo" :serviceTypeText="serviceTypeText" @handleWay="handleWay"
      @handleAddressInfo="handleAddressInfo" @handleTime="handleTime" @handleShipping="handleShipping" />

    <!-- 协议类 -->
    <!-- <xieyi-vue :agree="agree" @handleAgree="handleAgree" /> -->

    <!-- 底部悬浮按钮 -->
    <fixed-footer :systemInfo="systemInfo" :evaluate="evaluate" :displayPrice="displayPrice" :selectCoupon="selectCoupon"
      :serviceTypeText="serviceTypeText" @handlePriceDetailShow="handleLayerShow('priceDetailRef')"
      @handleSumbit="handleSumbit" />

    <!-- 对应弹窗 -->
    <view>
      <!-- 价格明细 -->
      <price-detail-layer ref="priceDetailRef" :evaluate="evaluate" :displayPrice="displayPrice" :selectCoupon="selectCoupon" />

      <!-- #ifdef MP-ALIPAY -->
      <!-- 直付通 进件插件 -->
      <bjhs-private-order-recycle :orderParams="bjhsOrderParams" ref="bjhsRef" @callback="handleBjhsOperate" />
      <!-- #endif -->

      <!-- 可用优惠券弹窗 -->
      <!-- <coupon-layer
        ref="couponRef"
        :selectCoupon="selectCoupon"
        :list="couponList"
        @handleCouponClick="handleCouponClick"
      /> -->

      <!-- 提交成功 -->
      <order-layer ref="orderRef" @handleOrder="handleOrder" />
      <!-- 取消挽留 -->
      <retain-cancel ref="retainRef" :selectCoupon="selectCoupon" @confirmBack="handleConfirmBack" />


    </view>

  </view>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import WeValidator from 'we-validator'
import {
  fetchRegionTree,
  getCreateOrder,
  fetchRecycleMethod,
  fetchUserCanUseList,
  fetchUserBonusList,
  fetchUserBonusDetail,
  fetchBjhsCreateOrder,
  getOrderUpdatePartnerInfo,
  canSyncSuhuishou,
  checkDoorService
} from '@/api'
import {
  parseTime, waitShowToast,
  wait,
} from '@/utils'
import regionTree from '@/utils/city.json'

import ProductInfo from './components/ProductInfo.vue'
import CouponVue from './components/Coupon.vue'
import RecycleMethod from './components/RecycleMethod.vue'
import XieyiVue from './components/Xieyi.vue'
import FixedFooter from './components/FixedFooter.vue'
import PriceDetailLayer from './components/PriceDetailLayer.vue'
import CouponLayer from './components/CouponLayer.vue'
import OrderLayer from './components/OrderLayer.vue'
import TipsVue from '@/pages/index/components/Tips.vue'
import ZhimaSuban from './components/ZhimaSuban.vue'
import RetainCancel from './components/RetainCancel.vue'
import {
  appid
} from '@/config'
import loadOpenid from '@/utils/smallAppOpenid'

export default {
  name: 'Assess',
  components: {
    ProductInfo, XieyiVue, RecycleMethod,
    FixedFooter,
    PriceDetailLayer,
    FixedFooter,
    CouponLayer,
    CouponVue,
    TipsVue,
    ZhimaSuban,
    OrderLayer,
    RetainCancel
  },

  computed: {
    ...mapGetters([
      'systemInfo', 'userInfo', 'location', 'geoLocation',
      'channel', 'recoveryMode'
    ]),
    ...mapState({
      evaluate: state => state.evaluate.evaluateResult
    }),

    serviceTypeText() {
      const text = this.wayIndex == 0 ? '取件' : '上门'
      return text
    },

    // 基础价格：evaluatePrice / 1.1，四舍五入到十位
    basePrice() {
      const price = this.evaluate.evaluatePrice / 1.1
      return Math.round(price / 10) * 10
    },

    // 显示价格：基础价格 + 加价券
    displayPrice() {
      return this.basePrice + this.selectCoupon.bonusValue
    },

    serviceTime() {
      if (this.bestDays && this.bestHours) {
        const text = parseTime(this.bestDays, '{m}月{d}日 (周{a}) ') + (this.bestHours + ":00 - " + (parseInt(this.bestHours) + 2) + ":00")
        return text
      }
      return ''
    },
    countDown() {
      const hours = Math.floor(this.remainingTime / 3600);
      const minutes = Math.floor((this.remainingTime % 3600) / 60);
      const seconds = this.remainingTime % 60;
      const countTime = {
        hours: hours.toString().padStart(2, '0'),
        minutes: minutes.toString().padStart(2, '0'),
        seconds: seconds.toString().padStart(2, '0')
      };
      return countTime
    }
  },

  async created() {
    this.initData()
    // console.log('-----当前估价商品----', this.evaluate)
    // this.loadUserInfo()
    // this.handleCouponGrent()
    // #ifndef MP-XHS
    this.getLocation()
    //#endif
    
    // this.loadRegionTree()
    this.initValidator()
    this.initAddressInfoValidator()
    // this.loadRecycleMethod()
    this.handleGetOpenId()
    await wait(500)
  },

  async onLoad(options) {
    console.log("=====onLoad====", options)
    
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight || 0
  },

  async onShow() {
    console.log("=====onShow====")
    console.log("页面栈长度:", getCurrentPages().length)
    console.log("当前页面:", getCurrentPages()[getCurrentPages().length - 1]?.route)
    // 重置提交标记
    this.isLeavingBySubmit = false
    
    clearInterval(this.timer);
    this.timer = null;
    this.timer = setInterval(this.updateTimer, 1000);
    await wait(100)
    if (!this.evaluate.productId) {
      this.uniRouter.redirectTo('/pages/category/index')
      return
    }
    // 获取加价券
    // this.loadBonusList()
    // 初始化加价券
    this.calculateBonus()
    this.userInfo.phone && (this.mobile = this.userInfo.phone)
    // 检查上门服务是否可用
    if (this.addressInfo.districtCode) {
      this.checkDoorServiceAvailable(this.addressInfo.districtCode)
    }
  },
  
  onBackPress(options) {
    console.log("=====onBackPress 拦截返回====", options, 'from:', options?.from)
    
    // 如果是提交订单后离开，不拦截
    if (this.isLeavingBySubmit) {
      console.log("提交订单后离开，允许返回")
      return false
    }
    
    console.log("显示挽留弹窗")
    // 使用 nextTick 确保弹窗能正常显示
    this.$nextTick(() => {
      this.handleLayerShow("retainRef")
    })
    // 返回 true 阻止默认返回行为
    return true
  },

  onHide() {
    console.log("=====onHide====")
  },
  
  onUnload() {
    // 页面卸载时清理定时器
    console.log('页面卸载', '是否提交后离开:', this.isLeavingBySubmit);
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    return false;
    // 如果不是提交订单后离开，尝试显示挡留弹窗（但可能已经太晚）
    if (!this.isLeavingBySubmit) {
      console.warn('用户未经 onBackPress 离开页面');
    }
  },

  data() {
    return {
      isShow: true,
      isLeavingBySubmit: false, // 标记是否是提交订单后离开
      showRetainDialog: false, // 控制弹窗显示
      statusBarHeight: 0, // 状态栏高度
      active: 1, // 当前回收方式
      wayList: [
        { "wayId": 1, "wayName": "顺丰包邮", "wayText": "顺丰包邮" },
        { "wayId": 2, "wayName": "上门回收", "wayText": "当面拿钱" },

      ],
      bjhsOrderParams: {
        show: false,
        serviceCategoryCode: 'PHONE_PAD_RECYCLE',
      },
      openId: "",
      mobile: '',
      name: '',
      wayIndex: 0,

      gegionTree: [],
      treeMap: { text: "label", value: "value" },
      categoryEnergy: {},


      validatorInstance: null,//校验
      addressInfoValidatorInstance: null,//校验用户收货信息

      zhima_orderNo: 0,
      zhima_payAfterUseChar: '',
      zhima_advanceCharge: 200,
      agree: true,
      districtCode: "",
      userData: {},

      couponList: [], // 优惠券列表
      selectCoupon: { bonusId: 1, bonusValue: 0 }, // 选中优惠券
      accountInfo: {
        accountName: "",
        accountNumber: ""
      },
      addressInfo: {
        province: "",
        city: "",
        district: "",
        districtCode: 0,
        address: "",
        userName: "",
        userPhone: "",
      },
      orderData: {},
      noVisit: false,
      remainingTime: 24 * 60 * 60,
      timer: null
    }
  },

  methods: {
    // 计算加价券
    calculateBonus() {
      if (!this.evaluate.evaluatePrice) return
      
      let bonusRate = 0
      let bonusName = ""
      if (this.wayIndex === 0) {
        // 顺丰包邮：15%
        bonusRate = 0.15
        bonusName = "限时加价15%"
      } else if (this.wayIndex === 1) {
        // 上门回收：10%
        bonusRate = 0.10
        bonusName = "限时加价10%"
      }
      
      // 加价券基于基础价格（/1.1后）计算
      this.selectCoupon.bonusName = bonusName
      this.selectCoupon.bonusValue = Math.round(this.basePrice * bonusRate)
    },

    //获取用户openId
    async handleGetOpenId() {
      const result = await loadOpenid()
      if (result.code === 200) {
        this.openId = result.data
      }
    },
    beforeleave() {
      this.isShow = false; //这个很重要，一定要先把弹框删除掉
      this.handleLayerShow("retainRef")
    },
    updateTimer() {
      if (this.remainingTime > 0) {
        this.remainingTime--;
        // 在这里更新 store，而不是在计算属性中
        const hours = Math.floor(this.remainingTime / 3600);
        const minutes = Math.floor((this.remainingTime % 3600) / 60);
        const seconds = this.remainingTime % 60;
        const countTime = {
          hours: hours.toString().padStart(2, '0'),
          minutes: minutes.toString().padStart(2, '0'),
          seconds: seconds.toString().padStart(2, '0')
        };
        this.$store.dispatch('evaluate/updateCountdown', countTime)
      } else {
        // 组件销毁前清除定时器
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    // 获取区域树
    loadRegionTree() {
      fetchRegionTree().then(({ data, code }) => {
        if (code === 200) {
          this.gegionTree = data || []
        }
      })
    },

    // 根据省市区名称从regionTree中获取对应的value（代码）
    getRegionCodes(provinceName, cityName, districtName) {
      let provinceCode = null;
      let cityCode = null;
      let districtCode = null;

      // 查找省份
      const province = regionTree.find(item => item.label === provinceName);
      if (province) {
        provinceCode = province.value.padEnd(6, '0');

        // 查找城市
        if (province.children && cityName) {
          const city = province.children.find(item => item.label === cityName);
          if (city) {
            cityCode = city.value.padEnd(6, '0');

            // 查找区县
            if (city.children && districtName) {
              const district = city.children.find(item => item.label === districtName);
              if (district) {
                districtCode = district.value.padEnd(6, '0');
              }
            }
          }
        }
      }

      return {
        provinceCode,
        cityCode,
        districtCode
      };
    },

    //初始化信息
    initData() {
      // #ifdef MP_ALIPAY
      my.setNavigationBar({
        backgroundColor: '#000000', // 想使用frontColor 这个字段必填
        frontColor: '#FFFFFF' // 设置文字及状态栏电量、日期等文字颜色
      })
      //#endif
    },


    // 获取定位
    async getLocation() {
      try {
        uni.showLoading({ title: '加载中', mask: false })

        let geoLocation = this.geoLocation
        if (!geoLocation.province) {
          const res = await this.$store.dispatch('userLocation/getLocation', true)
          if (res.code == -1) {
            const res = await this.$store.dispatch('userLocation/loadGeoLocation', true)
          }
          if (res.geoLocation && res.geoLocation.province) {
            geoLocation = res.geoLocation
          }
        }
        console.log("=============>",geoLocation)
        if (geoLocation.province) {
          this.addressInfo.districtCode = geoLocation.districtCode || 0,
            this.addressInfo.province = geoLocation.province || '',
            this.addressInfo.city = geoLocation.city || '',
            this.addressInfo.district = geoLocation.district || '',
            this.addressInfo.districtCode = geoLocation.adCode || '',
            this.addressInfo.address = geoLocation.address || ''
          // this.loadRecycleMethod()
        }
      } finally {

      }
    },

    //获取用户收货地址
    handleShipping() {
      const _this = this
      uni.chooseAddress({
        async success(res) {
          console.log('chooseAddress success', res);
          let telNumber = res.telNumber;
          if (telNumber == '020-81167888') {
            telNumber = "13912345678"
          }
          
          // 直辖市处理：如果是直辖市且城市名不包含"市"，则加上"市"
          const municipalities = ['北京', '上海', '天津', '重庆'];
          let provinceName = res.provinceName;
          if (municipalities.includes(provinceName) && provinceName && !provinceName.endsWith('市')) {
            provinceName = provinceName + '市';
          }

          // 从regionTree获取各级的value（代码）
          const { provinceCode, cityCode, districtCode } = _this.getRegionCodes(
            provinceName,
            res.cityName,
            res.countyName
          );

          const payload = {
            province: provinceName,
            city: res.cityName,
            district: res.countyName,
            provinceCode: provinceCode,
            cityCode: cityCode,
            districtCode: districtCode,
            address: res.detailInfo,
            userName: res.userName,
            userPhone: telNumber,
          }
          console.log("======地址===========>",payload)

          _this.addressInfo = payload
          _this.loadRecycleMethod()

        },
        fail: err => {
          console.log('chooseAddress fail', err);
        }
      })
    },

    //加载用户数据
    loadUserInfo() {
      fetchUserInfo().then(({ data, code }) => {
        if (code === 200) {
          this.userData = data || {}
        }
      })
    },

    // 获取加价券
    loadBonusList() {
      fetchUserCanUseList({
        amount: this.evaluate.evaluatePrice,
        bonusStatus: 1,
        productId: this.evaluate.productId,
      }).then(({ code, data }) => {
        if (code === 200) {
          this.couponList = data || []
          if (data.length) {
            this.selectCoupon = data[0]
          }
        }
      })
    },

    // 获取区域服务类型
    loadRecycleMethod() {
      uni.showLoading({ title: '加载中', mask: false })
      fetchRecycleMethod({
        province: this.addressInfo.province,
        city: this.addressInfo.city,
        district: this.addressInfo.district,
      }).then(({ data, code }) => {
        if (code === 200) {
          this.wayList = data
          if (data.length) {
            this.active = data.find(item => item.active).wayId
            if (this.active == 1) {
              this.noVisit = true
            } else {
              this.noVisit = false
            }
          }
        }
      })
    },

    //領取卡券
    handleCouponGrent(item) {
      console.log('-----領取卡券----', item)
      fetchUserReceiveBonus({
        activityId: "100001"
      }).then(({ data, code }) => {
        if (code === 200) {
          console.log(data)
          waitShowToast("领取成功");
          this.loadBonusList();
        }
      })
    },


    //时间
    handleTime(time) {
      this.time = time
    },

    // 切换回收方式
    handleWay(index) {
      this.wayIndex = index
      this.active = this.wayList[index].wayId
      // 根据回收方式计算加价券
      this.calculateBonus()
    },
    //点击协议
    handleAgree() {
      this.agree = !this.agree
    },

    // 弹窗显示
    handleLayerShow(ref) {
      console.log('========== 开始显示弹窗 ==========')
      console.log('弹窗 ref:', ref)
      console.log('组件实例:', this.$refs[ref])
      console.log('组件是否有 onOpen:', this.$refs[ref]?.onOpen)
      
      if (ref === 'retainRef') {
        this.showRetainDialog = true
        console.log('设置 showRetainDialog = true')
      }
      
      if (this.$refs[ref] && this.$refs[ref].onOpen) {
        console.log('调用 onOpen 方法')
        this.$refs[ref].onOpen()
        console.log('onOpen 调用完成')
      } else {
        console.error('❌ 弹窗组件不存在或没有 onOpen 方法:', ref)
        console.error('所有 refs:', Object.keys(this.$refs))
      }
      console.log('========== 显示弹窗结束 ==========')
    },
    // 弹窗隐藏
    handleLayerHide(ref) {
      this.$refs[ref].onClose()
      this.showRetainDialog = false
    },
    
    // 确认返回（用户点击“仍取消订单”）
    handleConfirmBack() {
      console.log('用户确认返回')
      // 标记为允许离开
      this.isLeavingBySubmit = true
    },

    onResize() {
      // page-meta resize 事件
    },
    
    // 自定义返回按钮点击
    handleCustomBack() {
      console.log('点击自定义返回按钮')
      
      // 如果是提交订单后离开，直接返回
      if (this.isLeavingBySubmit) {
        console.log('允许返回')
        uni.navigateBack()
        return
      }
      
      // 否则显示挽留弹窗
      console.log('显示挽留弹窗')
      this.handleLayerShow('retainRef')
    },

    // 选择加价券
    handleCouponClick(item) {
      this.selectCoupon = item
      this.handleLayerHide('couponRef')
    },

    // 省市区选中监听
    handleAddressInfo(addressInfo) {
      console.log('-----省市区选中监听----', addressInfo)
      this.addressInfo = addressInfo
      this.districtCode = addressInfo.districtCode
      // 检查上门服务是否可用
      if (addressInfo.districtCode) {
        this.checkDoorServiceAvailable(addressInfo.districtCode)
      }
    },

    // 检查上门服务是否可用
    async checkDoorServiceAvailable(districtCode) {
      try {
        const { code, data } = await checkDoorService({ districtCode })
        if (code === 200) {
          this.noVisit = !data.available
          if (!data.available && this.wayIndex === 1) {
            // 如果当前选择的是上门回收，但该区域不支持，自动切换到邮寄
            this.handleWay(0)
          }
        }
      } catch (error) {
        console.error('检查上门服务失败:', error)
      }
    },
    //校验
    initValidator() {
      // 实例化
      this.validatorInstance = new WeValidator({
        rules: {
          evaluateId: {
            required: true
          },
          appointStartTime: {
            required: true
          }
        },
        messages: {
          evaluateId: {
            required: '估价信息不存在',
          },
          appointStartTime: {
            required: '预约时间不存在',
          }
        }
      });
    },
    //校验用户收货信息
    initAddressInfoValidator() {
      // 实例化
      this.addressInfoValidatorInstance = new WeValidator({
        rules: {
          userName: {
            required: true
          },
          userPhone: {
            required: true,
            pattern: /^1[3-9]\d{9}$/
          },
          province: {
            required: true
          },
          city: {
            required: true
          },
          districtCode: {
            required: true
          },
          district: {
            required: true
          },
          address: {
            required: true
          }
        },
        messages: {
          userName: {
            required: '请输入联系人姓名',
          },
          userPhone: {
            required: '请输入联系电话',
            pattern: '请输入正确的手机号码'
          },
          province: {
            required: '请选择省份',
          },
          city: {
            required: '请选择城市',
          },
          district: {
            required: '请选择区域',
          },
          address: {
            required: '请输入详细地址',
          }
        }
      });
    },
    //格式化预约时间
    formatAppointTime() {
      const day = this.time[0]
      const hour = this.time[1]
      const appointEndTime = parseTime(day, "{y}-{m}-{d}") + " " + (parseInt(hour) + 2) + ":00:00"
      const appointStartTime = parseTime(day, "{y}-{m}-{d}") + " " + (parseInt(hour)) + ":00:00"
      return { appointEndTime, appointStartTime }
    },
    // 提交订单
    handleSumbit() {
      console.log('-----提交订单----', this.evaluate)
      if (!this.agree) {
        waitShowToast("请同意用户协议")
        return
      }
      const { evaluateId } = this.evaluate
      const { appointEndTime, appointStartTime } = this.formatAppointTime()

      let extendInfo = {
        bonusId: this.selectCoupon.bonusId,
        bonusPrice: this.recoveryMode == 0 ? this.selectCoupon.bonusValue : 0,
        openId: this.openId
      }
      if (this.noVisit && this.active == 2) {
        this.active = 1;
        this.wayIndex = 0;
        return;
      }
      if (!this.addressInfo.userPhone) {
        this.addressInfo.userPhone = this.userData.userPhone
      }
      const payload = {
        evaluateId: evaluateId,
        appointEndTime: appointEndTime,
        appointStartTime: appointStartTime,
        addressInfo: this.addressInfo,
        extendInfo,
        orderType: this.active,
        channel: JSON.stringify(this.channel) || "",
        accountInfo: this.accountInfo,
        orderPrice: this.displayPrice,
      }
      console.log("===============>创建订单", JSON.stringify(payload))

      if (!this.addressInfoValidatorInstance.checkData(this.addressInfo)) return;
      if (!this.validatorInstance.checkData(payload)) return;
      console.log("===============>创建订单", payload)


      uni.showLoading({ title: '提交中...', mask: true })

      this.loadCreateOrder(payload)
    },

    // 提交订单
    async loadCreateOrder(payload) {

      const res = await getCreateOrder(payload)

      if (res.code === 200) {
        if (res.data.orderNo) {
          this.orderData = res.data
          console.log('订单数据', this.orderData)
          // #ifdef MP-ALIPAY
          await this.bjhsCreateOrder(payload, res.data.orderNo)
          // #endif
          this.handleLayerShow("orderRef")
          const { source, orderNo, orderTime } = this.orderData
          const url = `/pages/order/logistics-detail?orderNo=${orderNo}`
          // 标记为提交订单后离开，不拦截返回
          this.isLeavingBySubmit = true
          uni.redirectTo({ url })
        }
      } else {
        waitShowToast(res.message)
      }
    },
    //点击订单详情
    handleOrder() {
      this.handleLayerHide("orderRef")
      const { source, orderNo, orderTime } = this.orderData
      const url = `/pages/order/logistics-detail?orderNo=${orderNo}`
      // 标记为提交订单后离开，不拦截返回
      this.isLeavingBySubmit = true
      uni.redirectTo({ url })
    },
    // 直付通进件回调
    handleBjhsOperate() {
      console.log('直付通进件成功回调执行');
    },

    // 格式化预约时间为直付通所需格式
    formatBestTime(appointStartTime) {
      if (!appointStartTime) return '';

      console.log('原始时间:', appointStartTime);

      // 处理不同的时间格式
      let date;
      if (typeof appointStartTime === 'string') {
        // 替换可能的格式问题，确保能被正确解析
        const timeStr = appointStartTime.replace(/\s+/g, ' ').trim();
        date = new Date(timeStr);

        // 如果解析失败，尝试手动解析
        if (isNaN(date.getTime())) {
          const match = timeStr.match(/(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})/);
          if (match) {
            const [, year, month, day, hour, minute, second] = match;
            date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day), parseInt(hour), parseInt(minute), parseInt(second));
          }
        }
      } else {
        date = new Date(appointStartTime);
      }

      console.log('解析后的日期对象:', date);

      if (isNaN(date.getTime())) {
        console.error('时间解析失败:', appointStartTime);
        return appointStartTime; // 如果解析失败，返回原始值
      }

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = date.getHours();
      const startHour = String(hour).padStart(2, '0');
      const endHour = String(hour + 1).padStart(2, '0');

      const result = `${year}-${month}-${day} ${startHour}:00-${endHour}:00`;
      console.log('格式化后的时间:', result);

      return result;
    },

    // 直付通创建订单
    async bjhsCreateOrder(payload, orderNo) {
      console.log("创建支付宝订单========>", payload, orderNo)
      if (payload.orderType == 2) {
        return;
      }
      try {
        const canSyncResult = await canSyncSuhuishou({
          cityCode: payload.addressInfo.cityCode,
          orderPrice: payload.orderPrice,
          userPhone: payload.addressInfo.userPhone
        });

        // 如果返回的结果不是false，则不能进行下去
        if (canSyncResult.data !== false) {
          console.log('canSyncSuhuishou 返回非false，停止创建订单:', canSyncResult);
          return;
        }

        console.log('canSyncSuhuishou 返回false，继续创建订单');
      } catch (error) {
        console.error('canSyncSuhuishou 调用失败:', error);
        // 如果API调用失败，可以选择继续或停止，这里选择停止
        return;
      }

      const options = {
        request: {
          itemList: [{
            productCode: 'PHONE_PAD',
            productName: this.evaluate.productName,
            productItemId: this.evaluate.productId,
            categoryCode: this.evaluate.categoryId,
            assessAmount: payload.orderPrice,
          }],
          userInfo: {
            userId: this.openId,
            name: payload.addressInfo.userName,
            mobile: payload.addressInfo.userPhone,
          },
          addressInfo: {
            source: payload.orderType,
            name: payload.addressInfo.userName,
            mobile: payload.addressInfo.userPhone,
            provinceCode: payload.addressInfo.provinceCode,
            cityCode: payload.addressInfo.cityCode,
            districtCode: payload.addressInfo.districtCode,
            address: payload.addressInfo.address,
            bestTime: this.formatBestTime(payload.appointStartTime),
          },
          assessInfo: {
            assessAmount: payload.orderPrice,
            orderSourceAppId: appid,
          },
          orderChannel: 'ONLINE',
          orderCenterInfo: {
            energy: this.categoryEnergy[this.evaluate.categoryId] || this.categoryEnergy[0] || '0',
          },
        },
        appId: appid,
        serviceCategoryCode: 'PHONE_PAD_RECYCLE',
        serviceCode: '3C_CHUSHOUYA',
        outOrderId: orderNo,
        title: this.evaluate.productName,
        detailedPath: `/pages/order/logistics-detail?orderNo=${orderNo}`,
      }
      console.log('直付通创建订单参数========>', options)

      const bjhsPlugin = requirePlugin('bjhsPlugin')

      return new Promise(resolve => {
        bjhsPlugin.createOrder(options, res => {
          console.log('下单的回调结果=========>', res)
          if (res.success) {
            getOrderUpdatePartnerInfo({
              orderNo,
              orderCenterNo: res.data.orderCenterNo,
            })
            my.requestSubscribeMessage({
              entityIds: [
                'cf80d7d81cc64690a9a5bd9a83006121',
                '2c58c268251a431d8fce62ddbec0728b',
                'cf097bc6f1ad4ce8903c60ad541c2ef8'
              ],
              success: res => {
                console.log('接口调用成功的回调', res);
              },
              fail: err => {
                console.log('接口调用失败的回调', err);
              }
            });
          }

          resolve(res)
        }, false)
      })
    }
  },


}
</script>

<style lang="scss" scoped>
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  
  .navbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 16rpx;
    
    .navbar-left {
      width: 64rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 8rpx;
    }
    
    .navbar-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
    
    .navbar-right {
      width: 80rpx;
    }
  }
}

.evaluate {
  background-color: #F6F7F9;
  padding: 0rpx 32rpx 214rpx;
  padding-top: calc(var(--status-bar-height) + 88rpx);
}
</style>
